package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.leyou.common.constants.MQConstants.RoutingKey.*;
import static com.leyou.common.constants.MQConstants.Exchange.*;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.item.service
 * @date 2019/6/27 17:42
 * @description:
 **/
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private AmqpTemplate amqpTemplate;


    public PageResult<SpuDTO> queryGoods(String key, Boolean saleable, Integer rows, Integer page) {

        //分页
        PageHelper.startPage(page,rows);

        //添加查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%");
        }

        if (saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }

        //查询数据
        List<Spu> list = spuMapper.selectByExample(example);

        //解析数据
        PageInfo<Spu> info = new PageInfo<>(list);

        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(list, SpuDTO.class);

        //处理数据
        handleCategoryNameAndBrandName(spuDTOS);

        return new PageResult<>(info.getTotal(),spuDTOS);
    }

    private void handleCategoryNameAndBrandName(List<SpuDTO> spuDTOS) {

        for (SpuDTO spuDTO : spuDTOS) {

            //处理categoryName
            String categoryName = categoryService.queryCategoryByCids(spuDTO.getCategoryIds())
                    .stream().map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
            //处理brandName
            Brand brand = brandService.queryBrandByBid(spuDTO.getBrandId());
            spuDTO.setBrandName(brand.getName());
        }
    }


    /**
     * 新增商品
     * @param spuDTO
     * @return
     */

    @Transactional
    public void insertGoods(SpuDTO spuDTO) {

        //新增spu表的数据
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        int count = spuMapper.insertSelective(spu);
        if (count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //新增spu_detail表的数据
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        count = spuDetailMapper.insertSelective(spuDetail);
        if (count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //新增sku表的数据
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        List<Sku> skus = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            skuDTO.setSpuId(spu.getId());
            skus.add(BeanHelper.copyProperties(skuDTO,Sku.class));
        }
        count = skuMapper.insertList(skus);
        if (count!=skus.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 商品下架，更新spu和sku表
     * @param spuId
     * @param saleable
     * @return
     */
    public void updateSpuSaleable(Long spuId, Boolean saleable) {

        //更新spu表
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count!=1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //更新sku表的enable
        Sku sku = new Sku();
        sku.setEnable(saleable);
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",spuId);
        count = skuMapper.updateByExampleSelective(sku, example);
        int size =skuMapper.selectCountByExample(example);
        if (count!=size){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        String key= saleable ? ITEM_UP_KEY:ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME,key,spuId);

    }

    /**
     * spuDetail数据回显
     * @param spuId
     * @return
     */
    public SpuDetailDTO querySpuDetail(Long spuId) {

        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spuId);
        if (spuDetail==null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);
    }

    /**
     * sku数据回显
     * @param spuId
     * @return
     */
    public List<SkuDTO> queryListSku(Long spuId) {

        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> list = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list,SkuDTO.class);


    }

    /**
     * 修改商品提交
     * @param spuDTO
     * @return
     */
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {

        //判断spuID是否存在
        Long spuId = spuDTO.getId();
        if (spuId==null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        //删除sku表的数据
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        int size = skuMapper.selectCount(sku);
        if (size>0){
            int count = skuMapper.delete(sku);
            if (count!=size){
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }


        //修改spu表数据
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count!=1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //修改spuDetail表数据
        SpuDetailDTO spuDetail = spuDTO.getSpuDetail();
        SpuDetail detail = BeanHelper.copyProperties(spuDetail, SpuDetail.class);
        count = spuDetailMapper.updateByPrimaryKeySelective(detail);
        if (count!=1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }


        //修改sku表数据
        List<SkuDTO> skus = spuDTO.getSkus();
        List<Sku> list = skus.stream().map(skuDTO -> {
            skuDTO.setEnable(false);
            skuDTO.setSpuId(spuId);
            return BeanHelper.copyProperties(skuDTO,Sku.class);
        }).collect(Collectors.toList());
       count= skuMapper.insertList(list);
       if (count!=list.size()){
           throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
       }
    }

    /**
     * 根据spuID查询spu
     * @param spuId
     * @return sku的集合
     */
    public SpuDTO querySpuBySpuId(Long spuId) {

        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        spuDTO.setSpuDetail(querySpuDetail(spuId));
        spuDTO.setSkus(queryListSku(spuId));

        return spuDTO;

    }

    /**
     * 根据skuId查询sku信息
     * @param ids
     * @return
     */
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> skus = skuMapper.selectByIdList(ids);
        if (skus==null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skus,SkuDTO.class);

    }

    @Transactional
    public void minusStock(Map<Long, Integer> cartMap) {
        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();

            Sku sku = skuMapper.selectByPrimaryKey(skuId);
            Sku record = new Sku();
            record.setId(skuId);
            record.setStock(sku.getStock()-num);
            int count = skuMapper.updateByPrimaryKeySelective(record);


            if(count != 1){
                throw new RuntimeException("库存不足");
            }
        }
    }



    public void plusStock(Map<Long, Integer> map) {
        for (Map.Entry<Long, Integer> entry : map.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            Sku sku = skuMapper.selectByPrimaryKey(skuId);

            Sku record = new Sku();
            record.setId(skuId);
            record.setStock(sku.getStock()+num);

            int count = skuMapper.updateByPrimaryKeySelective(record);

            if(count != 1){
                throw new RuntimeException("库存添加失败！");
            }

        }

    }
}
